package org.jaronsource.framework.plugins.staticpage;

import java.io.File;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;

public class StaticPageUtils {

	public static String convertToHtmlFileName( String requestURI ) {

		if ( requestURI.endsWith( StaticPageContext.getInstance().getStaticPageExt() ) ) return requestURI;

		StringBuilder result = new StringBuilder();

		String URI = StringUtils.substringBefore( requestURI, "?" );
		URI = StringUtils.substringBefore( URI, StaticPageContext.getInstance().getRequestExt() );

		String params = StringUtils.substringAfter( requestURI, "?" );
		params = StringUtils.replace( params, "=", "!" );
		params = StringUtils.replace( params, "&", "+" );

		result.append( URI );
		if ( !StringUtils.isBlank( params ) ) {
			result.append( "-" );
			result.append( params );
		}
		result.append( StaticPageContext.getInstance().getStaticPageExt() );

		return result.toString();
	}

	public static String convertFromHtmlFileName( String requestURI ) {

		if ( requestURI.endsWith( StaticPageContext.getInstance().getRequestExt() ) ) return requestURI;

		StringBuilder result = new StringBuilder();

		String URI = StringUtils.substringBefore( requestURI, "-" );

		String params = StringUtils.substringAfter( requestURI, "-" );
		params = StringUtils.substringBefore( params, StaticPageContext.getInstance().getStaticPageExt() );
		params = StringUtils.replace( params, "!", "=" );
		params = StringUtils.replace( params, "+", "&" );

		result.append( URI );
		result.append( StaticPageContext.getInstance().getRequestExt() );
		if ( !StringUtils.isBlank( params ) ) {
			result.append( "?" );
			result.append( params );
		}

		return result.toString();
	}

	public static void clean( HttpServletRequest request, String path ) {

		if ( path == null ) return;
		StaticPageContext staticPageContext = StaticPageContext.getInstance();
		String staticPageRootRealPath = request.getSession().getServletContext().getRealPath( staticPageContext.getStaticPageRoot() );
		if ( !path.startsWith( "/" ) ) path = "/" + path;
		File targetFile = new File( staticPageRootRealPath + path );
		targetFile.delete();
	}
}
